package com.heqiang.spring.beans.factory.support;

import com.heqiang.spring.beans.BeansException;
import com.heqiang.spring.beans.factory.DisposableBean;
import com.heqiang.spring.beans.factory.config.SingletonBeanRegistry;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class DefaultSingletonBeanRegistry implements SingletonBeanRegistry {

    protected static final Object NULL_OBJECT = new Object();

    Map<String, Object> singletonBeanMap = new ConcurrentHashMap<>();

    private Map<String, DisposableBean> disposableBeanMap = new HashMap<>();


    @Override
    public Object getSingleton(String name) {
        return singletonBeanMap.get(name);
    }

    @Override
    public void registerSingleton(String name, Object singletonObject) {
        singletonBeanMap.put(name,singletonObject);
    }

    protected void addSingleton(String name,Object bean){
        singletonBeanMap.put(name, bean);
    }

    public void registerDisposableBean(String beanName,DisposableBean disposableBean) {
        disposableBeanMap.put(beanName, disposableBean);
    }


    public void destroySingletons () {
        Set<String> keySet = this.disposableBeanMap.keySet();
        Object[] disposableBeanNeams = keySet.toArray();

        for (int i = disposableBeanNeams.length-1; i>= 0;i--) {
            Object beanName = disposableBeanNeams[i];
            DisposableBean disposableBean = disposableBeanMap.remove(beanName);
            try {
                disposableBean.destroy();
            } catch (Exception e) {
                throw new BeansException("destroy销毁失败发生异常，beanName="+beanName);
            }

        }
    }


}
